// pages/confirm_buy/confirm_buy.js
var utils = require('../../utils/util.js');
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    disabled:false,
    totalFee:0,
    order:[],
    address: false,
    goods_list: [],
    coupon: false,
    bargain: false,
    dis_type:0,
    msg:''//用户留言
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this
    // var orderNo = '2018031756880';//options.order_no
    var orderNo = options.order_no
    _this.setData({
      orderNo:orderNo
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var _this = this
    app.getUserInfo(function (cb) {
      _this.getConfirmOrderInfo(_this.data.orderNo)
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  getTotalFee: function () {
    var _this = this
    var totalFee = 0;
    var goods_list = _this.data.goods_list
    for (var i = 0; i < goods_list.length; i++) {
      totalFee += parseFloat(goods_list[i]['price']) * parseInt(goods_list[i]['count'])
    }
    if (_this.data.dis_type == 1) {
      //优惠券有效
      if (_this.data.coupon) {
        totalFee -= parseFloat(_this.data.coupon.price)
      }
    } else if (_this.data.dis_type == 2) {
      if (_this.data.bargain) {
        totalFee -= parseFloat(_this.data.bargain.bargain_count)
      }
    }
    totalFee += parseFloat(_this.data.order.freight)
    _this.setData({
      totalFee:totalFee
    })
  },

  /**
   * 获取默认地址
   */
  getConfirmOrderInfo: function (order_no) {
    var _this = this
    wx.request({
      url: app.globalData.requestip + "&c=Order&a=getConfirmOrderInfo",
      data:{
        order_no:order_no
      },
      header: app.globalData.header,
      success: function (res) {
        if (res.data.code == 0) {
          var dis_type = 0
          var bargainPrice = res.data.bargain.bargain_count
          var couponPrice = res.data.coupon.price
          if (bargainPrice != null && bargainPrice != '') {
            bargainPrice = parseInt(bargainPrice)
          } else {
            bargainPrice = 0
          }
          if (couponPrice != null && couponPrice != '') {
            couponPrice = parseInt(couponPrice)
          } else {
            couponPrice = 0
          }

          if (couponPrice >= bargainPrice && couponPrice > 0) {
            dis_type = 1
          } else if (couponPrice < bargainPrice && couponPrice > 0) {
            dis_type = 2
          }
          _this.setData({
            order: res.data.order,
            address: res.data.address,
            goods_list: res.data.goods_list,
            coupon: res.data.coupon,
            bargain: res.data.bargain,
            dis_type: dis_type
          })
          _this.getTotalFee()
        } else {
          utils.loadFail(res)
        }
      },
      fail: function (res) {
        utils.loadRequestFail(res)
      }
    })
  },

  //修改地址
  changeAddress:function () {
    var orderNo = this.data.orderNo
    wx.navigateTo({
      url: '../addr_list/addr_list?checkType=2&order_no='+orderNo
    })
  },

  //砍价
  tapBargain:function (e) {
    var order_no = this.data.orderNo
    wx.navigateTo({
      url: '../price/price?order_no='+order_no
    })
  },

  //添加砍价记录
  tapAddBargain:function () {
    var _this = this
    wx.request({
      url: app.globalData.requestip + "&c=Order&a=addBargainInfo",
      data: {
        order_no: _this.data.order.order_no
      },
      header: app.globalData.header,
      success: function (res) {
        if (res.data.code == 0) {
          wx.navigateTo({
            url: '../price/price?order_no=' + _this.data.orderNo,
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {},
          })
        } else {
          utils.loadFail(res)
        }
      },
      fail: function (res) {
        utils.loadRequestFail(res)
      }
    })
  },

  //切换优惠券
  changeCoupon:function (e) {
    if (e.detail.value == 'coupon') {
      this.setData({
        dis_type: 1
      })
    } else {
      this.setData({
        dis_type: 2
      })
    }
    this.getTotalFee()
  },

  tapRule:function () {
    wx.navigateTo({
      url: '../rules/rules',
    })
  },
  
  pay:function (e)
  {
    var _this = this
    if (_this.data.address) {
      _this.data.msg
      _this.setData({
        disabled: true
      })
      console.log(_this.data.msg)
      var discount_id = 0
      if (_this.data.dis_type == 1) {
        discount_id = _this.data.coupon.id
      } else if (_this.data.dis_type == 2) {
        discount_id = _this.data.bargain.id
      }
      wx.request({
        url: app.globalData.requestip + "&c=Order&a=pay",
        data: {
          order_no: _this.data.orderNo,
          dis_type: _this.data.dis_type,
          discount_id: discount_id,
          addr_id: _this.data.address.id,
          freight: _this.data.order.freight,
          gid: _this.data.goods_list[0].gid,
          msg:_this.data.msg
        },
        // method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT  
        header: app.globalData.header,
        success: function (res) {
          if (res.data.code == 0) {
            var data = JSON.parse(res.data.jsApiParameters)
            var pkg = 'prepay_id=' + res.data.prepay_id;
            wx.requestPayment({
              timeStamp: data.timeStamp,
              nonceStr: data.nonceStr,
              package: data.package,
              signType: data.signType,
              paySign: data.paySign,
              success: function (res) {
                console.log(res)
                if (res.errMsg == 'requestPayment:ok') {
                  wx.showToast({
                    title: '支付成功',
                    duration: 2000,
                    mask: true,
                    success: function () {
                    },
                    fail: function () { },
                    complete: function () {
                      wx.redirectTo({
                        url: '../order_list/order_list?currentTab=2',
                      })
                    }
                  })
                }
              },
              fail: function (res) {
                console.log(res)
                if (res.errMsg == 'requestPayment:fail cancel') {
                  wx.showToast({
                    title: '支付取消',
                    duration: 2000,
                    mask: true,
                    success: function () {
                    },
                    fail: function () { },
                    complete: function () {
                      wx.redirectTo({
                        url: '../order_list/order_list?currentTab=1',
                      })
                    }
                  })

                }
              }
            })
          } else {
            utils.loadFail(res)
          }
        }
      });
    } else  {
      wx.showToast({
        title: '请先选择收货地址',
        duration: 3000,
      })
    }
  },

  bindMsgBlur: function (e) {
    var _this = this
    _this.setData({
      msg:e.detail.value
    })
  }

})